<?php

function loadmodules() {
	//Check all necessary files exist and functions are defined

	global $settings;
	global $db_config;

	if (!isset($settings['wikiuser']))
		error("Set variable: wikiuser");
	else if (!isset($settings['wikipass']))
		error("Set variable: wikipass");
	else if (!isset($settings['flickr_key']))
		error("Set variable: flickr_key");
	else if (!isset($db_config['db_host']))
		error("Set variable: db_host");
	else if (!isset($db_config['db_username']))
		error("Set variable: db_username");
	else if (!isset($db_config['db_password']))
		error("Set variable: db_password");
	else if (!isset($db_config['db_name']))
		error("Set variable: db_name");

	if (!include_once('config.inc.php'))
		error("missing file 'config.inc.php'");
	else if (!include_once('functions.inc.php'))
		error("missing file 'functions.inc.php'");
	else if (!include_once('wikipedia.php'))
		error("missing file 'wikipedia.php'");
	else if (!include_once('flickr.php'))
		error("missing file 'flickr.php'");
	else if (!function_exists('get_related_terms'))
		error("missing function 'get_related_terms'");
	else if (!function_exists('get_images'))
		error("missing function 'get_related'");
}

function mainlogic() {
	$starttime = microtime(true);

	if( isset( $_GET[ "q" ] ))
		$search = $_GET[ "q" ];
	else
		$search = "ucla"; // Testing purposes

	//Alan: connect to local database
	$resource_local = connectToDatabase();

	$cache_hits = 0;
	//Alan: get related terms
	$terms = get_related_terms($resource_local, $search, $cache_hits );
// 	$terms = array( array( "ucla", null ), array( "kevin love", null ), 
// 			array( "usc", null) , array( "cal tech", null) ,
// 			array( "stanford", null ), array("vint cerf", null ), 
// 			array( "john wooden", null ), 
// 			array("kleinrock", null) );

	
	// Convert into a format that get_images() expects
// 	$strip_terms = array();
// 	foreach( $terms as $t )
// 	  $strip_terms[] = $t[ 0 ];
	$img_html = get_images( $terms, $search, 1 );

 	foreach( $img_html as $v ) {
 		$tag = htmlentities($v["tag"]);
 		$url = $v["url"];
 		$web = $v["web"];
		$url_l = $v[ "url_l" ]; // Larger image
		$context = htmlentities($v["context"]);
		
		$example= "example1";
 		echo "<div content=\" 
			<ul>	<li class='searchterm'><b>$tag</b></li>
				<li><a href='$web'>Flickr</a></li>
				<li><a href='$url_l' rel='$example'> Lightbox </a></li>
				<li>$context</li>
				</ul>\" class='draggable' class='ui-widget-content'>
 			<img src='$url'></img><ul tag=$tag><li class='searchterm'>$tag</li></ul></div>";





 		echo "\n";
	}

	$latency = timespan_output($starttime, microtime(true), 'bottomOutput');

	if ($resource_local)
	{
		$remote_addr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'localhost';
		metrics_log($resource_local, $remote_addr, $search, $cache_hits, round($latency * 1000));
	}

}

loadmodules();
mainlogic();

?>
